package nckd.wnqjt.tmc.tda.plugin.form;

import com.alibaba.fastjson.JSON;
import kd.bos.ai.util.JsonUtil;
import kd.bos.algo.*;
import kd.bos.algo.input.CollectionInput;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.qing.Field;
import kd.bos.entity.qing.*;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.form.control.IQingAnalysis;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.mvc.SessionManager;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.report.ReportShowParameter;
import kd.bos.servicehelper.QueryServiceHelper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhujintao
 * @date 2024/11/05
 * @desc 资金存量趋势
 */

public class FundStockTrendQingDataProvider extends AbstractFormPlugin implements IQingDataProvider {
    private static Log log = LogFactory.getLog(FundStockTrendQingDataProvider.class);


    /**
     * 获取表头信息定义
     */
    @Override
    public QingMeta getMeta(String pageId) {
        String entityKey = "bei_bankbalance";
        QingMeta meta = new QingMeta();
        EntryEntity entity = new EntryEntity();
        entity.setKey(entityKey); //实体名(唯一标识)	是
        entity.setName(new LocaleString("余额查询")); //实体别名	是
        entity.setPkFieldName("id");//主键名称	是
        meta.addEntryEntity(entity);
////"yearMonth", "totalfund", "constrainedfund", "availablefund"
        Field column = new Field();
        column.setEntity(entityKey);//字段所属实体key	否
        column.setKey("yearMonth");// 字段名(唯一标识)	是
        column.setFieldType(QingFieldType.String.toNumber()); //数据类型	是
        column.setName(new LocaleString("年月")); //字段别名	是
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("totalfund");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("当前余额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("constrainedfund");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("受限资金"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("availablefund");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("定存金额"));
        meta.addColumn(column);

        /*column = new Field();
        column.setEntity(entityKey);
        column.setKey("bankenterprisebalance");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("银企余额"));
        meta.addColumn(column);

        column = new Field();
        column.setEntity(entityKey);
        column.setKey("notbankenterprisebalance");
        column.setFieldType(QingFieldType.Number.toNumber());
        column.setName(new LocaleString("非银企余额"));
        meta.addColumn(column);*/

        /*column = new Field();
        column.setEntity(entityKey);
        column.setKey("bizdate");
        column.setFieldType(QingFieldType.DateTime.toNumber());
        column.setName(new LocaleString("日期"));
        meta.addColumn(column);*/
        return meta;
    }

    /**
     * 获取轻分析数据
     *
     * @param startRow 起始行
     * @param limit    每页的数据量
     * @return 轻分析数据
     */
    @Override
    public QingData getData(String pageId, int startRow, int limit) {
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter");
        if (qFilter != null) {
            //通过此方法拿到过滤参数
            Map<String, Object> filterParam = (Map) JSON.parseObject(qFilter, Map.class);
        }
        //实体账户当前余额+受限资金管理中银行账户是虚拟户受限金额+定期存款管理中定期账户是虚拟户的投资理财
        /**
         * ***************************************************************
         */
        //获取当前日期往前一年的日期
        LocalDate currentdate = LocalDate.now(); // 获取当前日期
        Period period = Period.ofMonths(-11); // 设置一个代表月的周期
        LocalDate lastMonthDate = currentdate.plus(period); // 计算上一周期的日期
        LocalDate firstDayOfMonth = lastMonthDate.with(TemporalAdjusters.firstDayOfMonth());
        Date enddate = Date.from(currentdate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date startdate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
        List<String> yearMonths = getYearMonthsBetween(firstDayOfMonth, currentdate);
        List<LocalDate> monthEndsBetween = getMonthEndsBetween(firstDayOfMonth, currentdate);

        List<QFilter> qFilterList = new ArrayList<>();
        for (LocalDate localDate : monthEndsBetween) {
            Date startdate1 = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
            LocalDateTime enddateTime = localDate.atTime(23, 59, 59);
            Date enddate1 = Date.from(enddateTime.atZone(ZoneId.systemDefault()).toInstant());
            QFilter dateFilter = new QFilter("bizdate", QCP.large_equals, startdate1).and("bizdate", QCP.less_equals, enddate1);
            qFilterList.add(dateFilter);
        }

        QFilter beiBankbalanceFilter = null;
        //子公司当前余额+母公司当前余额 排除结算中心
        QFilter finorgtype = new QFilter("number", QCP.equals, "FI-015");
        DynamicObject queryOne = QueryServiceHelper.queryOne("bd_finorgtype", "id", finorgtype.toArray());
        if (queryOne != null) {
            Object pkValue = queryOne.getLong("id");
            beiBankbalanceFilter = new QFilter("bank.finorgtype.id", QCP.not_equals, pkValue);
        }
        QFilter dateFilter = qFilterList.get(0);
        for (int i = 1; i < qFilterList.size(); i++) {
            QFilter qFilter1 = qFilterList.get(i);
            dateFilter.or(qFilter1);
        }
        QFilter beiBankbalanceFilter1 = beiBankbalanceFilter.and(dateFilter);
        log.info("资金存量趋势分析余额查询条件 " + beiBankbalanceFilter1.toString());
        String beiBankbalanceSelectField = "id,company.id companyid,company.number companynumber,company.name companyname" +
                ",accountbank.id accountbankid,accountbank.bankaccountnumber bankaccountnumber,bizdate,nckd_depositbalance,amount,freezebalance,datasource";
        DataSet beiBankbalanceDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bei_bankbalance", beiBankbalanceSelectField, beiBankbalanceFilter1.toArray(), null);
        beiBankbalanceDataSet = beiBankbalanceDataSet.addField("TO_CHAR(bizdate,'yyyy-MM')", "yearmonth");

        //获取符合条件的虚拟账户列表
        QFilter acctstatusfilter = new QFilter("acctstatus", QCP.not_equals, "closed").and("isvirtual", QCP.equals, true);
        String getAcctSelectedFieds = "id,company,openorg,issetbankinterface,bank,bankaccountnumber,isvirtual,name,currencyname,defaultcurrency,opendate,acctstatus,acctstyle,accttype,acctproperty,manager,acctname,finorgtype";
        DataSet acctDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "bd_accountbanks", getAcctSelectedFieds, acctstatusfilter.toArray(), null);
        List<String> isvirtualAccountNoList = new ArrayList<>();
        while (acctDataSet.hasNext()) {
            Row next = acctDataSet.next();
            String bankaccountnumber = next.getString("bankaccountnumber");
            isvirtualAccountNoList.add(bankaccountnumber);
        }
        //受限资金管理
        String amRestrictedfundsmanagerSelectField = "id,org.id companyid,org.number companynumber,org.name companyname,bankacct.id accountbankid,bankacct.bankaccountnumber bankaccountnumber,unrestrictedamt,restricteddate";
        //增加受限
        QFilter businesstype = new QFilter("businesstype", QCP.equals, "1").and("billstatus", QCP.equals, "C")
                .and("bankacct.bankaccountnumber", QCP.in, isvirtualAccountNoList);
                //.and("restricteddate", QCP.large_equals, startdate).and("restricteddate", QCP.less_equals, enddate);
        DataSet amRestrictedfundsmanagerDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "am_restrictedfundsmanager", amRestrictedfundsmanagerSelectField, businesstype.toArray(), null);
        amRestrictedfundsmanagerDataSet = amRestrictedfundsmanagerDataSet.addField("TO_CHAR(restricteddate,'yyyy-MM')", "yearmonth");

        //定期存款处理
        QFilter cimDepositQfilter = new QFilter("billstatus", QCP.equals, "C").and("finaccount", QCP.in, isvirtualAccountNoList);
                //.and("intdate", QCP.large_equals, startdate).and("intdate", QCP.less_equals, enddate);
        String cimDepositSelectField = "id,org.id companyid,org.number companynumber,org.name companyname,settleaccount.id accountbankid,settleaccount.bankaccountnumber bankaccountnumber,surplusamount,intdate";
        DataSet cimDepositDataSet = QueryServiceHelper.queryDataSet(this.getClass().getName(), "cim_deposit", cimDepositSelectField, cimDepositQfilter.toArray(), null);
        cimDepositDataSet = cimDepositDataSet.addField("TO_CHAR(intdate,'yyyy-MM')", "yearmonth");

        //创建一个空的DataSet
        String[] fieldNames = {"yearMonth", "totalfund", "constrainedfund", "availablefund"};
        DataType[] dataTypes = {DataType.StringType, DataType.BigDecimalType, DataType.BigDecimalType, DataType.BigDecimalType};
        Collection<Object[]> coll = new ArrayList<Object[]>();
        //获取每个月的最大日期转为map
        Map<String, String> dateMap = monthEndsBetween.stream().collect(Collectors.toMap(k -> k.getYear() + "-" + String.format("%02d", k.getMonthValue()),
                v -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(
                        Date.from(v.atTime(23, 59, 59).atZone(ZoneId.systemDefault()).toInstant()))));

        //yearMonths 是最近一年的年月字符串
        for (String yearMonth : yearMonths) {
            String filter = "yearmonth = '" + yearMonth + "'";
            String date = dateMap.get(yearMonth);
            String filter1 = "restricteddate <= TO_DATE('" + date + "','yyyy-MM-dd HH:mm:ss')";
            String filter2 = "intdate <= TO_DATE('" + date + "','yyyy-MM-dd HH:mm:ss')";
            DataSet amountSum = beiBankbalanceDataSet.copy().filter(filter).groupBy().sum("amount").finish();
            DataSet unrestrictedamtSum = amRestrictedfundsmanagerDataSet.copy().filter(filter1).groupBy().sum("unrestrictedamt").finish();
            DataSet surplusamountSum = cimDepositDataSet.copy().filter(filter2).groupBy().sum("surplusamount").finish();
            Object[] objArr = new Object[4];
            objArr[0] = yearMonth;
            objArr[1] = new BigDecimal(0);
            objArr[2] = new BigDecimal(0);
            objArr[3] = new BigDecimal(0);
            while (amountSum.hasNext()) {
                Row next = amountSum.next();
                objArr[1] = next.getBigDecimal("amount");
            }
            while (unrestrictedamtSum.hasNext()) {
                Row next = unrestrictedamtSum.next();
                objArr[2] = next.getBigDecimal("unrestrictedamt");
            }
            while (surplusamountSum.hasNext()) {
                Row next = surplusamountSum.next();
                objArr[3] = next.getBigDecimal("surplusamount");
            }
            coll.add(objArr);
        }
        beiBankbalanceDataSet.close();
        amRestrictedfundsmanagerDataSet.close();
        cimDepositDataSet.close();
        RowMeta rowMeta = RowMetaFactory.createRowMeta(fieldNames, dataTypes);
        CollectionInput inputs = new CollectionInput(rowMeta, coll);
        DataSet resultDataSet = Algo.create(this.getClass().getName()).createDataSet(inputs);

        QingData data = null;
        if (startRow < 200) {
            data = new QingData();
            Map<String, Integer> dataindex = new HashMap<String, Integer>();
            //"yearMonth", "totalfund", "constrainedfund", "availablefund"
            dataindex.put("yearMonth", 0);
            dataindex.put("totalfund", 1);
            dataindex.put("constrainedfund", 2);
            dataindex.put("availablefund", 3);

            data.setDataindex(dataindex);

            List<Object[]> rows = new ArrayList<Object[]>();
            while (resultDataSet.hasNext()) {
                Row row = resultDataSet.next();
                Object[] obj = new Object[4];
                obj[0] = row.getString("yearMonth");
                obj[1] = row.getBigDecimal("totalfund");
                obj[2] = row.getBigDecimal("constrainedfund");
                obj[3] = row.getBigDecimal("availablefund");
                //obj[4] = row.getDate("bizdate");
                /*Timestamp timestamp = (Timestamp) row.get("bizdate");
                long time = timestamp.getTime();
                obj[4] = time;*/
                rows.add(obj);
            }
            data.setRows(rows);
        }
        return data;
    }

    /**
     * 获取两个日期之间的全部年月
     *
     * @param startDate
     * @param endDate
     * @return
     */
    private List<String> getYearMonthsBetween(LocalDate startDate, LocalDate endDate) {
        List<String> yearMonthList = new ArrayList<>(); // 创建一个列表来存储结果
        // 从起始日期开始，遍历到结束日期
        while (!startDate.isAfter(endDate)) { // 只要startDate不晚于endDate
            yearMonthList.add(startDate.getYear() + "-" + String.format("%02d", startDate.getMonthValue())); // 获取年-月格式
            startDate = startDate.plusMonths(1); // 增加一个月
        }
        return yearMonthList;
    }

    /**
     * 获取两个日期之间的每个月的最大日
     *
     * @param start
     * @param end
     * @return
     */
    public static List<LocalDate> getMonthEndsBetween(LocalDate start, LocalDate end) {
        List<LocalDate> monthEnds = new ArrayList<>();
        while (!start.isAfter(end)) {
            if (start.getYear() == end.getYear() && start.getMonth() == end.getMonth()) {
                monthEnds.add(end);
                start = start.plusMonths(1);
            } else {
                monthEnds.add(start.with(TemporalAdjusters.lastDayOfMonth()));
                start = start.plusMonths(1);
            }
        }
        return monthEnds;
    }


    @Override
    public void setFilterParameter(String filterParameter) {
        IPageCache pageCache = getPageCache();
        pageCache.put("qFilter", filterParameter);

    }

    @Override
    public String getFilterParameter() {
        return getPageCache().get("qFilter");
    }

    /**
     * 获取动态表单联查信息
     *
     * @param pageId
     * @param ctrKey
     * @return
     */
    @Override
    public List<QingLinkageInfo> getLinkageInfo(String pageId, String ctrKey) {
        //return IQingDataProvider.super.getLinkageInfo(pageId, ctrKey);
        List<QingLinkageInfo> infos = new ArrayList<QingLinkageInfo>();
        QingLinkageInfo info = new QingLinkageInfo();
        Map<String, String> formKey = new HashMap<>();
        AppInfo appInfo = AppMetadataCache.getAppInfo("bei");
        //String appId = this.getView().getFormShowParameter().getAppId();
        formKey.put("AppId", appInfo.getAppId()); //需要打开的表单所在应用的id
        //String formId = this.getView().getFormShowParameter().getFormId();
        formKey.put("FormId", "nckd_totalfundsrpt"); //需要打开的表单的id
        formKey.put("System", "IERP");
        formKey.put("CtrKey", ctrKey);
        info.setFormKey(JsonUtil.encodeToString(formKey));
        info.setFormDisplayName("资金明细报表");//联查到表单的显示名称
        info.setFormPrimaryKey("id");//联查到表单的主键
        infos.add(info);//可以添加多个QingLinkageInfo对象
        this.getView().getPageCache().put("qingViewControlKey", ctrKey);//必要语句!
        return infos;
    }

    /**
     * <p>调用此接口，触发业务逻辑，具体业务联查实现此接口<p/>
     *
     * @param ids    轻分析得到动态表单需要联査的1d的集合
     * @param pageId
     * @param formId
     * @param appId
     */
    @Override
    public void fireLinkageInfo(List<String> ids, String pageId, String formId, String appId) {
        //IQingDataProvider.super.fireLinkageInfo(ids, pageId, formId, appId);
        /*具体的表单打开逻辑，业务自己去实现
        ids:联查到的主键的值
        pageId:触发联査的页面的pageId，可用于找到触发联査的页面: FormView view = (FormView)Sessiomanager.getCurrent().getView(pageId)
        formId:联查到的表单的id
        appId:联查到的表单所在应用的Id
        */

        /*注意: 如果需要使用芒穹的view.showForm 方式打开表单，需要添加以下代码*/
        // 组装 FormShomParaneter(披照业务场景亲实现)
        ReportShowParameter reportShowParameter = new ReportShowParameter();
        reportShowParameter.getOpenStyle().setShowType(ShowType.Modal);
        reportShowParameter.setAppId(appId);
        reportShowParameter.setFormId(formId);//报表标识
        //拿过滤条件，进行取数
        String qFilter = getPageCache().get("qFilter"); //从仪表板进去 拿不到
        //通过此方法拿到过滤参数
        Map<String, Object> filterParam = new HashMap<>();
        // 设置报表过滤条件
        ReportQueryParam reportQueryParam = new ReportQueryParam();
        //FilterInfo filterInfo = new FilterInfo();
        //filterInfo.addFilterItem("nckd_orgview", filterParam.get("nckd_orgview"));
        //filterInfo.addFilterItem("nckd_org", filterParam.get("nckd_org"));
        //filterInfo.addFilterItem("nckd_currency", filterParam.get("nckd_currency"));
        //filterInfo.addFilterItem("bizdate", filterParam.get("nckd_querydate"));
        //filterInfo.addFilterItem("nckd_amountunit", filterParam.get("nckd_amountunit"));
        filterParam.put("id", ids);
        //reportQueryParam.setFilter(filterInfo);
        reportQueryParam.setCustomParam(filterParam);
        reportShowParameter.setQueryParam(reportQueryParam);

        /*******************************showForm必要的代码******************************************/
        IFormView view = SessionManager.getCurrent().getView(pageId);
        String ctrKey = this.getView().getPageCache().get("qingViewControlKey");
        if (ctrKey != null) {
            if (view.getControl(ctrKey) instanceof IQingAnalysis) {
                //设计器的场景，直接showForm
                view.showForm(reportShowParameter);
                return;
            }
        }
        //其他场景需要，返回FormShowParameter，由轻分析来 showForm
        this.getView().setClientReturnData(ListShowParameter.toJsonString(reportShowParameter));
        /*******************************showForm必要的代码******************************************/
    }
}